package cn.edu.swu.miniwebsvr.core;

import cn.edu.swu.miniwebsvr.handler.DefaultHandler;
import cn.edu.swu.miniwebsvr.handler.EchoHandler;
import cn.edu.swu.miniwebsvr.handler.TimeHandler;
import java.util.HashMap;
import java.util.Map;

public class Config {
    private final int port = 8080;
    private final String webRoot = "webroot";
    private final Map<String, Handler> handlerMap = new HashMap<>();

    private Config() {
        handlerMap.put("/", new DefaultHandler());
        handlerMap.put("/time", new TimeHandler());
        handlerMap.put("/echo", new EchoHandler());
    }

    public static Config getInstance() {
        return Holder.INSTANCE;
    }

    private static class Holder {
        private static final Config INSTANCE = new Config();
    }

    public int getPort() {
        return port;
    }

    public String getWebRoot() {
        return webRoot;
    }

    public Handler getHandler(String url) {
        // 首先尝试精确匹配
        Handler handler = handlerMap.get(url);
        if (handler != null) {
            return handler;
        }

        // 如果精确匹配失败，检查是否是静态文件请求（包含文件扩展名）
        if (url.contains(".")) {
            return new DefaultHandler();
        }

        // 如果没有匹配的路由，返回null，由Router处理
        return null;
    }
}